
const ServerResponse = require('@root/middlewares/resHandler');
const User = require('@root/models/user.model')


exports.getProfile = async ctx => {
    const { profile } = ctx.state;
    const { user: authenticateUser } = ctx.state;
    if (authenticateUser) {
        const user = await User.findById(authenticateUser.id);
        if (!user) {
            ctx.body = ServerResponse.createByErrorMsgAndData('获取失败', { profile: profile.toProfileJSONFor(false) })

        }
        ctx.body = ServerResponse.createBySuccessMsgAndData('获取成功', { profile: profile.toProfileJSONFor(user) })
    } else {
        ctx.body = ServerResponse.createByErrorMsgAndData('获取失败', { profile: profile.toProfileJSONFor(false) })
    }

}

exports.follow = async ctx => {
    const {profile:target,user: authenticateUser } = ctx.state;
    const user = await User.findById(authenticateUser.id);
    if (!user) {
        ctx.body = ServerResponse.createByErrorMsg('没有找到当前用户')

    }
    await user.addFollower(target._id);

    const updateProfile = {
        username: target.username,
        bio: target.bio,
        image: target.image,
        following: target.assertFollower(user.id)
    }
    ctx.body = ServerResponse.createBySuccessMsgAndData('关注成功',{profile:updateProfile})
}


exports.unfollow = async ctx => {
    const {profile:target,user: authenticateUser } = ctx.state;
    const user = await User.findById(authenticateUser.id);
    if (!user) {
        ctx.body = ServerResponse.createByErrorMsg('没有找到当前用户')

    }
    await user.removeFollower(target._id);
    const updateProfile = {
        username: target.username,
        bio: target.bio,
        image: target.image,
        following: target.assertFollower(user.id)
    }
    
    ctx.body = ServerResponse.createBySuccessMsgAndData('取消关注成功',{profile:updateProfile})
}


exports.getFollowers = async ctx=>{
    const {user:authenticateUser} = ctx.state;
    // ctx.body = user;
    const user = await User.findById(authenticateUser.id)
    if(!user){
        ctx.body = ServerResponse.createByErrorMsg('没有找到当前用户')
    }
    const ids = user.followers;
    const resultUsers = await User.find({ _id: { $in: ids } })
    const users = []
    for (let target of resultUsers) {
        users.push(target.toProfileJSONFor())
    }
    ctx.body = {users}
}
